package com.mxprojects.io
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	
	public class ServerHandler
	{
		public static const EVENT_DATA_RECEIVED:String = "DATA_RECEIVED";
		
		public static var BASE_URL:String;
		
		//change this if you would like to see the data going in and out
		private const TRACE_RAW_DATA:Boolean = false;
		private const SCRIPT_DIRECTORY:String = "scripts/";
		
		private var fileVars:URLVariables = new URLVariables();
		private var dataHolder:Object;
		private var finishFunctions:Array = new Array();
		
		public function ServerHandler(){}
		
		public function transmitData(fileName:String, dataToSend:Object = null, loadRequest:Boolean = true):URLRequest {						
			//form a URL to send to the server
			var fileRequest:URLRequest = createRequest(fileName);
			var fileLoader:URLLoader = new URLLoader();
			
			//if the script needs data, break it down in here
			if(dataToSend != null){
				//reset the file vars
				fileVars = new URLVariables();
				
				for(var key:String in dataToSend){
					//url+= "&" + key + "=" + dataToSend[key];
					fileVars[key] = dataToSend[key];
				}
								
				//if we have stuff to send make sure we are posting it
				fileRequest.method = URLRequestMethod.POST;
				fileRequest.data = fileVars;
			}
			
			if(TRACE_RAW_DATA){
				trace("DATA FILE VARS:", fileVars);
			}
			
			//clear the data
			fileVars = null;
			
			if(loadRequest){
				//send it out
				fileLoader.load(fileRequest);
				
				//listen for the response
				fileLoader.addEventListener(Event.COMPLETE, processServerData);
				fileLoader.addEventListener(IOErrorEvent.IO_ERROR, serverError);
				
				return null;
			}else{
				return fileRequest;
			}
		}
		
		public function listenForData(functionToCallWhenDataReceived:Function):void {
			//setup the finish function
			finishFunctions.push(functionToCallWhenDataReceived);
		}
		
		private function createRequest(fileName:String):URLRequest {
			var randomGarbage:Number = Math.random()*12231980;
			var url:String = BASE_URL + SCRIPT_DIRECTORY + fileName +"?random=" + randomGarbage;
			var fileRequest:URLRequest = new URLRequest(url);
			
			return fileRequest;
		}
		
		private function processServerData(event:Event):void {
			var dataToDecode:String = event.target.data;
			if(TRACE_RAW_DATA){
				trace("DATA COMING IN:", dataToDecode, "\n\n");
			}
			
			if(dataToDecode == ""){
				handleFunctions();
				return;
			}
			
			//AS3 doesn't like the first &, trim it if it's there - legacy purposes
			if(dataToDecode.substring(0,1) == "&"){
				dataToDecode = dataToDecode.substring(1);
			}
			fileVars = new URLVariables();
			fileVars.decode(dataToDecode);
			
			//assign the data to a private var
			dataHolder = fileVars;
			
			//take care of the things that happen after we get data
			handleFunctions();
		}
		
		private function handleFunctions():void {
			//run the function that's supposed to run once the server gets data
			var finishEvent:CustomEvent = new CustomEvent(EVENT_DATA_RECEIVED, dataHolder);
			
			for(var i:int = 0; i < finishFunctions.length; i++){
				finishFunctions[i](finishEvent);
			}
			
			//kill the function array
			finishFunctions = new Array();
			
			//clear the data
			dataHolder = null;
		}
		
		private function serverError(event:IOErrorEvent):void {
			trace("There was an error loading data: ", event.text);
		}

	}
}